/**
 * Created by lumix on 2015/4/22.
 */
var express = require('express');
var router = express.Router();
var Promise = require('promise');
var logger = require('log4js').getLogger('activity');
var commonUtils = require('./../../utils/commonUtils');
var activityService = require('../service/ActivityService')
var worksService = require('../service/WorksService')
var attentionService = require('../service/AttentionService');
var articleService = require('../service/ArticleService');
var config = require('../../../config')
var multiparty = require('multiparty');
var util = require('util');
var fs = require('fs');
var imageinfo = require('imageinfo');

//活动列表
router.post('/index',function(req,res,next){
    var pageNo = req.body.pageNo;
    if(!pageNo) {
        pageNo = 1;
    }
    var pageSize = 5;
    activityService.queryPage(pageNo,pageSize).then(function(as){
        var data = {};
        if(as){
            //计算时间
            var now = new Date();
            as.forEach(function(item){
                console.log(item);
                var endTime = item.startTime;
                var diff = commonUtils.dateDiff(endTime,now);
                if(diff<0){
                    item.dateDiff = 0;
                }else{
                    item.dateDiff = diff;
                }
                //计算活动图片大小
                if(item&&item.imgUrl){
                    var imageData = fs.readFileSync(config.main.fileUploadPath+item.imgUrl);
                    var info = imageinfo(imageData);
                    item.imageWidth = info.width;
                    item.imageHeight = info.height;
                }
            })

            data.activitys = as;
            res.json({'success':true,'data':data});
        }else{
            res.json({'success':false,'msg':'查询失败'});
        }
    },function(err){
        console.log(err)
        res.json({'success':false,'msg':'网络异常'});
    })
})
//活动详情
router.post('/info',function(req,res,next){
    var activityId = req.body.activityId;
    var memberId = req.body.memberId;
    if(!activityId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }

    activityService.getActivity(activityId).then(function(activity){
        if(activity){
            //获取时间差
            var now = new Date();
            var endTime = activity.endTime;

            var dateDiff = commonUtils.dateDiff(now,endTime);

            if(dateDiff<=0){dateDiff=0;}
            if(now>endTime){
                activity.joinFlag = true;
            }else{
                activity.joinFlag = false;
            }
            activity.dateDiff = dateDiff;
            return Promise.resolve(activity);
        }else{
            return Promise.resolve(null);
        }
    }).then(function(activity){
        if(activity){
            if(memberId){
                return worksService.checkJoin(memberId,activityId).then(function(works){
                    //if(works&&works.length>0){
                    //    activity.joinFlag = true;
                    //}else{
                    //    activity.joinFlag = false;
                    //}
                    return Promise.resolve(activity);
                })
            }else{
                activity.joinFlag = false;
                return Promise.resolve(activity);
            }
        }else{
            return Promise.resolve(null);
        }
    }).then(function(activity){

        if(activity){
            var data = {};
            data.activity = activity;
            res.json({'success':true,'data':data});
        }else{
            res.json({'success':false,'msg':'查询失败'});
        }
    },function(err){
        console.log(err);
        logger.error(err);
        res.json({'success':false,'msg':'网络异常'});
    })


})

//参赛作品
router.post('/works',function(req,res,next){
    var activityId = req.body.activityId;
    var pageNo = req.body.pageNo;
    var type = req.body.type;
    var pageSize = 5;
    if(!pageNo){pageNo = 1;}
    if(!type){type = 1;}
    if(!activityId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    worksService.queryWorkPage(activityId,pageNo,pageSize,type).then(function(works){
            if(works){
                var data = {};
                data.works = works;
                res.json({'success':true,'data':data});
            }else{
                res.json({'success':false,'msg':'操作失败'});
            }
    },function(err){
        console.log(err);
        res.json({'success':false,'msg':'网络异常'});
    })

})

router.post('/workInfo',function(req,res,next){
    var memberId = req.body.memberId;
    var workId = req.body.workId;
    if(!workId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    worksService.getById(workId).then(function(work){
        if(work){
            return Promise.resolve(work);
        }else{
            return Promise.resolve(null);
        }
    }).then(function(work){
        if(work){
            var workMId = work.memberId;
            if(memberId){
                return attentionService.checkAttention(memberId,workMId,1).then(function(result){
                    if(result&&result.length>0){
                        work.attentionFlag = true;
                        return Promise.resolve(work);
                    }else{
                        work.attentionFlag = false;
                        return Promise.resolve(work);
                    }
                })
            }else{
                return Promise.resolve(work);
            }

        }else{
            return Promise.resolve(null);
        }
    }).then(function(work){
        if(work){
            if(memberId){
                return worksService.checkCollect(workId,memberId).then(function(result){
                    if(result&&result.length>0){
                        work.collectFlag = true;
                        return Promise.resolve(work);
                    }else{
                        work.collectFlag = false;
                        return Promise.resolve(work);
                    }
                })
            }
        }else{
            return Promise.resolve(null);
        }
    }).then(function(work){
        if(work){
            if(memberId){
                return worksService.checkLike(workId,memberId).then(function(result){
                    if(result&&result.length>0){
                        work.likeFlag = true;
                        return Promise.resolve(work);
                    }else{
                        work.likeFlag = false;
                        return Promise.resolve(work);
                    }
                })
            }
        }else{
            return Promise.resolve(null);
        }
    }).then(function(work){
        if(work){
            var data = {};
            data.work = work;
            res.json({'success':true,'data':data});
        }else{
            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        res.json({'success':false,'msg':'网络异常'});
    })
})

//收藏作品
router.post('/collect',function(req,res,next){
    var memberId = req.body.memberId;
    var workId = req.body.workId;
    if(!memberId||!workId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    worksService.collect(workId,memberId).then(function(col){
        if(col){
            res.json({'success':true});
        }else{
            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        console.log(err);
        logger.erro(err);
        res.json({'success':false,'msg':'网络异常'});
    })

})

router.post('/unCollect',function(req,res,next){
    var memberId = req.body.memberId;
    var workId = req.body.workId;
    if(!memberId||!workId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    worksService.unCollect(workId,memberId).then(function(col){
        if(col){
            res.json({'success':true});
        }else{
            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        console.log(err);
        logger.erro(err);
        res.json({'success':false,'msg':'网络异常'});
    })

})
//点赞
router.post('/like',function(req,res,next){
    var memberId = req.body.memberId;
    var workId = req.body.workId;
    if(!memberId||!workId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    worksService.like(workId,memberId).then(function(like){
        if(like){
            res.json({'success':true});
        }else{
            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        console.log(err);
        logger.erro(err);
        res.json({'success':false,'msg':'网络异常'});
    })

})

router.post('/unLike',function(req,res,next){
    var memberId = req.body.memberId;
    var workId = req.body.workId;
    if(!memberId||!workId){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    worksService.unLike(workId,memberId).then(function(like){
        if(like){
            res.json({'success':true});
        }else{
            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        console.log(err);
        logger.erro(err);
        res.json({'success':false,'msg':'网络异常'});
    })

})
//评论
router.post('/comment',function(req,res,next){
    var memberId = req.body.memberId;
    var workId = req.body.workId;
    var content = req.body.content;
    if(!memberId||!workId||!content){
        res.json({'success':false,'msg':'参数缺失'});
        return;
    }
    worksService.comment(workId,memberId,content).then(function(comment){
        if(comment){
            res.json({'success':true,'commentId':comment.insertId});
        }else{
            res.json({'success':false,'msg':'操作失败'});
        }
    },function(err){
        console.log(err);
        logger.erro(err);
        res.json({'success':false,'msg':'网络异常'});
    })

})

//相信内容
router.get('/detail',function(req,res,next){
    var activityId = req.query.activityId;
    activityService.getActivity(activityId).then(function(activity){
        if(activity){
            var data = {};
            data.activity = activity;
            res.render('shoot/views/activity',data);
        }else{
            res.state(404).end();
        }
    },function(err){
        console.log(err);
        logger.error(err);
        res.state(404).end();
    })
})

router.get('/winnersList',function(req,res,next){
    var activityId = req.query.activityId;
    activityService.getActivity(activityId).then(function(activity){
        if(activity){
            var data = {};
            data.activity = activity;
            res.render('shoot/views/winners',data);
        }else{
            res.state(404).end();
        }
    },function(err){
        console.log(err);
        logger.error(err);
        res.state(404).end();
    })
})
//报名
router.post('/join',function(req,res,next){
    var form = new multiparty.Form();
    form.encoding = 'utf-8';
    form.uploadDir = config.main.fileUploadPath;
    form.parse(req, function(err, fields, files) {
        var activityId = fields.activityId[0];
        var workId = null
        if(fields.workId){
            workId = fields.workId[0]
        }
        var memberId = fields.memberId[0];
        var title = null
        if(fields.title){
            title = fields.title[0]
        }
        var content = null;
        if(fields.content){
            content = fields.content[0]
        }
        var realName = fields.realName[0];
        var phone = fields.phone[0];
        var mail = fields.mail[0];
        var type = fields.type[0];
        new Promise(function(fulfil,reject){
            if(err){
                reject(files);
            }else{
                fulfil(files);
            }
        }).then(function(files){
                var queue = [];
                //var file = files.upload[0];
                if(files.upload){
                    files.upload.forEach(function(item,i){
                        queue.push(articleService.getFileName(item,i));
                    })

                    return Promise.all(queue);
                }else{
                    return Promise.resolve(null);
                }

            }).then(function(fileName){
                var work = {};
                work.id = workId;
                work.activityId = activityId;
                work.memberId = memberId;
                work.title = title;
                work.content = content;
                work.realName = realName;
                work.phone = phone;
                work.mail = mail;
                work.flag = type;
                if(work.id){
                    work.updateTime = new Date();
                }else{
                    work.createTime = new Date();
                }

                if(fileName){
                    if(fileName.length==1){
                        work.imgUrl = fileName[0];
                    }else{
                        work.imgUrl = fileName[1];
                    }
                    if(fileName.length==2){
                        work.bak4 = fileName[0];
                    }

                }
                return Promise.resolve(work);
            }).then(function(work){
                if(!work.id){
                    return worksService.save(work).then(function(result){
                        if(result){
                            result.isSave = true;
                            return Promise.resolve(result);
                        }else{
                            return Promise.resolve(null);
                        }
                    })
                }else{
                    return worksService.update(work).then(function(result){
                        if(result){
                            return Promise.resolve(result);
                        }else{
                            return Promise.resolve(null);
                        }
                    })
                }
            }).then(function (work) {
                if(work&&work.isSave){
                    return activityService.getActivity(activityId).then(function (r) {
                        if(r){
                            r.currentNum++;
                            return activityService.update(r).then(function () {
                                return Promise.resolve(work);
                            })
                        }else{
                            return Promise.resolve(work);
                        }
                    })
                }else{
                    return Promise.resolve(work);
                }
            }).then(function(work){
                if(work){
                    res.json({'success':true});
                }else{
                    res.json({'success':false,'msg':'操作失败'});
                }
            }, function (err) {
                console.log(err);
                logger.error(err);
                res.json({'success':false,'msg':'网络异常'});
            })


    })
})

router.post('/getJoinWork', function (req,res,next) {
    var memberId = req.body.memberId;
    var activityId = req.body.activityId;
    worksService.getJoinWork(memberId,activityId).then(function (w) {

        if(w){
            res.json({'success':true,'work':w});
        }else{
            res.json({'success':true});
        }
    }, function (err) {
        logger.error(err);
        res.json({'success':false,'msg':'网络异常'});
    })
})


module.exports = router;
